package com.ruoyi.leave.controller;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.leave.entity.LeaveInfo;
import com.ruoyi.leave.service.LeaveInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import vip.lsjscl.flowboot.common.ResponseData;
import vip.lsjscl.flowboot.workflow.entity.DKRuntimeTask;
import vip.lsjscl.flowboot.workflow.service.DKRuntimeTaskService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 请假信息控制器
 *
 * @author zhangxingju
 * @date 2025/02/13
 */
@RestController
@RequestMapping("/workflow/leave")
@RequiredArgsConstructor
public class LeaveInfoController {

    private final LeaveInfoService leaveService;

    private final DKRuntimeTaskService taskService;

    /**
     * 获取我的申请列表
     */
    @GetMapping("/my-applications")
    public ResponseData myApplications(@RequestParam Map<String, Object> params) {
        return leaveService.getMyApplications(params);
    }

    /**
     * 获取待办任务列表
     */
    @GetMapping("/todo-tasks")
    public ResponseData todoTasks() {
        // 获取当前用户的待办任务
        ResponseData todoTasks = leaveService.getTodoTasks();
        // 将业务ID列表传入service层查询
        return todoTasks;
    }

    /**
     * 获取已办任务列表
     */
    @GetMapping("/done-tasks")
    public ResponseData doneTasks() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取当前用户运行时已完成的任务
        List<DKRuntimeTask> completedRuntimeTasks = taskService.getCompletedRuntimeTasks(loginUser.getUserId().toString(), loginUser.getDeptId().toString());

        // 合并两个列表中的业务ID
        List<String> businessIds = new ArrayList<>(completedRuntimeTasks.stream()
                .map(DKRuntimeTask::getBusinessId)
                .toList());

        return leaveService.getDoneTasks(businessIds);
    }

    /**
     * 保存草稿
     */
    @PostMapping("/save-draft")
    public ResponseData saveDraft(@RequestBody LeaveInfo leaveInfo) {
        leaveInfo.setStatus("DRAFT");
        return leaveService.saveOrUpdate(leaveInfo);
    }

    /**
     * 提交申请
     */
    @PostMapping("/submit")
    public ResponseData submit(@RequestBody LeaveInfo leaveInfo) {
        leaveInfo.setStatus("PENDING");
        return leaveService.submitLeaveApplication(leaveInfo);
    }

    /**
     * 获取申请详情
     */
    @GetMapping("/detail")
    public ResponseData getDetail(@RequestParam String id) {
        return leaveService.getLeaveDetail(id);
    }

    /**
     * 删除申请
     */
    @DeleteMapping("/delete")
    public ResponseData delete(@RequestParam String id) {
        return leaveService.deleteLeaveApplication(id);
    }
} 